//
//  AddressViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-9-26.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "AddressViewController.h"
#define darkColor UIColorFromRGB(0x453d35)
#define lightColor UIColorFromRGB(0x999999)
#define lineColor UIColorFromRGB(0xe7ded7)

@interface AddressViewController ()

@end

@implementation AddressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.titleLabel.text = @"填写收货地址";

    float h = 0;
    if (IOS7) {
        h = 20;
    }

    UIButton * saveBtn = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-50, h, 50, UI_NAVIGATION_BAR_HEIGHT) btnNorImage:nil btnHighlightImage:nil btnTitle:@"保存" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [saveBtn addTarget:self action:@selector(saveAddress) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:saveBtn];

    [self createViews];
    
    [self getDataWithDict:@{@"OrderID":_orderID} api:API_GETADDRESS];
}

- (void)createViews{
    backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT)];
    backScrollView.delegate = self;
    backScrollView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:backScrollView];

    nameTF = [self createTextFieldWithHeight:0 placeholder:@"收货人姓名"];
    phoneTF = [self createTextFieldWithHeight:44 placeholder:@"手机号码"];
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    codeTF = [self createTextFieldWithHeight:44*2 placeholder:@"邮政编码"];
    codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [self createBtnCellWithString:@"省、市、区" height:44*3 tag:198700];
//    [self createBtnCellWithString:@"街道" height:44*4 tag:198701];

    addressPlaceHolder = [UILabel initLabelText:@"详细地址" andRect:CGRectMake(20,44*4+12,100,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:lightColor andTextAlignment:NSTextAlignmentLeft];
    [backScrollView addSubview:addressPlaceHolder];

    addressTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 44*4+4, UI_SCREEN_WIDTH-40, 60)];
    addressTV.backgroundColor = [UIColor clearColor];
    addressTV.delegate = self;
    addressTV.font = [UIFont systemFontOfSize:15];
    [backScrollView addSubview:addressTV];

    for (int i = 1; i < 6; i++) {
        if (i != 5) {
            UIView * line = [[XDTools sharedXDTools] createSeparatorLineWithRect:CGRectMake(0, i*44, UI_SCREEN_WIDTH, .5f)];
            [backScrollView addSubview:line];
        }else{
            UIView * line = [[XDTools sharedXDTools] createSeparatorLineWithRect:CGRectMake(0, 4*44+100, UI_SCREEN_WIDTH, .5f)];
            [backScrollView addSubview:line];
        }

    }

    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH,UI_MAINSCREEN_HEIGHT);


    addressView = [[AddressView alloc] initWithFrame:self.contentView.frame];
    addressView.delegate  =self;
    addressView.hidden = YES;
    [self.view addSubview:addressView];
}


- (UITextField *)createTextFieldWithHeight:(float)height placeholder:(NSString *)placeholder{
    UITextField * tf = [[UITextField alloc] initWithFrame:CGRectMake(20, height+12, UI_SCREEN_WIDTH-40, 20)];
    tf.font = [UIFont systemFontOfSize:15];
    tf.placeholder = placeholder;
    tf.delegate = self;
    [backScrollView addSubview:tf];

    return tf;
}

- (void)createBtnCellWithString:(NSString *)str height:(float)height tag:(int)tag{
    cityLB = [UILabel initLabelText:str andRect:CGRectMake(20, height+12, 200, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:darkColor andTextAlignment:NSTextAlignmentLeft];
    [backScrollView addSubview:cityLB];

    UIImageView * arrow = [[UIImageView alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-27.5f, 15.5f+height, 15/2.0f, 25/2.0f)];
    arrow.image = [UIImage imageNamed:@"arrow_cell"];
    [backScrollView addSubview:arrow];

    UIButton * btn = [UIButton initButton:CGRectMake(0, height, UI_SCREEN_WIDTH, 44) btnNorImage:nil btnHighlightImage:nil btnTitle:nil titleColor:nil titleFont:nil];
//    btn.backgroundColor = [UIColor redColor];
    btn.tag = tag;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [backScrollView addSubview:btn];
}



- (void)saveAddress{
    if (!nameTF.text.length) {
        [XDTools showTips:@"请输入收货人姓名" toView:self.contentView];
        return;
    }

    if (nameTF.text.length < 2 || nameTF.text.length > 10) {
        [XDTools showTips:@"请输入有效姓名" toView:self.contentView];
        return;
    }

    if (!phoneTF.text.length) {
        [XDTools showTips:@"请输入手机号" toView:self.contentView];
        return;
    }

    if (![XDTools chickIphoneNumberRight:phoneTF.text]) {
        [XDTools showTips:@"请输入有效手机号" toView:self.contentView];
        return;
    }

    if (!codeTF.text.length) {
        [XDTools showTips:@"请输入邮政编码" toView:self.contentView];
        return;
    }

    if (codeTF.text.length != 6) {
        [XDTools showTips:@"邮政编码位数不正确" toView:self.contentView];
        return;
    }

    if (!addressTV.text.length) {
        [XDTools showTips:@"请输入详细地址" toView:self.contentView];
        return;
    }
    


    NSDictionary * dic = @{@"ReceivePerson": nameTF.text,
                           @"ReceivePhone": phoneTF.text,
                           @"ReceiveAddr": addressTV.text,
                           @"ReceiveCity": cityLB.text,
                           @"ReceivePostcode": codeTF.text,
                           @"OrderID": _orderID};

    [self getDataWithDict:dic api:API_ADDRESS];
}

-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

        if([[tempDic objectForKey:@"status"]intValue] == 1){
            
            if ([api isEqualToString:API_ADDRESS]) {
                
                [XDTools showTips:@"保存地址成功" toView:self.contentView];
                
                [_delegate addressIsOK];
                
                [self performSelector:@selector(backPrePage) withObject:nil afterDelay:1];
                
            }else{
                
                [self refreshViewsWithDict:tempDic[@"data"]];
                
            }

        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];

        }

    }];

    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

- (void)refreshViewsWithDict:(NSDictionary *)dict{
    nameTF.text = dict[@"ReceivePerson"];
    phoneTF.text = dict[@"ReceivePhone"];
    codeTF.text = dict[@"ReceivePostcode"];
    if ([dict[@"ReceiveCity"] length]) {
        cityLB.text = dict[@"ReceiveCity"];
    }
    addressTV.text = dict[@"ReceiveAddr"];
    if (addressTV.text.length) {
        addressPlaceHolder.hidden = YES;
    }
}

- (void)btnClick{
    [nameTF resignFirstResponder];
    [phoneTF resignFirstResponder];
    [codeTF resignFirstResponder];;
    [addressTV resignFirstResponder];
    addressView.hidden = NO;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    [UIView animateWithDuration:.3f animations:^{
        backScrollView.contentOffset = CGPointMake(0, 100);
    }];
}

- (void)textViewDidChange:(UITextView *)textView{

    if (textView.text.length) {
        addressPlaceHolder.hidden = YES;
    }else{
        addressPlaceHolder.hidden = NO;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.isDragging) {
        [nameTF resignFirstResponder];
        [phoneTF resignFirstResponder];
        [codeTF resignFirstResponder];
        [addressPlaceHolder resignFirstResponder];
        [addressTV resignFirstResponder];
    }
}


#pragma mark - AddressView Delegate
-(void)chooseAddressWithProvince:(NSString *)province city:(NSString *)city area:(NSString *)area{
    cityLB.text = [NSString stringWithFormat:@"%@%@%@",province,city,area];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
